package org.demo.javascript;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

/**
 * 在 java 中执行 javascript
 * @author  
 * @date    2010-12-26
 * @file    org.demo.javascript.JsMain.java
 */
public class JsMain {
	public static void main(String[] args) {
		
		String js = "println('Hello world!');"
			+ "function getDatetime(){"
			+ " var date = new Date();"
			+ " var year = date.getFullYear();"
			+ " var month = date.getMonth() + 1;"
			+ " var day = date.getDate();"
		    + " var hour = date.getHours();"
		    + " var minute = date.getMinutes();"
		    + " var second = date.getSeconds();"
			+ " if (month < 10){ month = '0' + month;}"
			+ " if (day < 10){day = '0' + day;}"
			+ " if (hour < 10){hour = '0' + hour;}"
			+ " if (minute < 10){minute = '0' + minute;}"
			+ " if (second < 10){second = '0' + second;}"
			+ " return year + '-' + month + '-' + day + ' '" 
			+ "             + hour + ':' + minute + ':' + second;"
			+ "}";
		
		ScriptEngineManager manager = new ScriptEngineManager();
		ScriptEngine engine = manager.getEngineByName("javascript");
		try {
			engine.eval(js);
			
			if (engine instanceof Invocable){
				Invocable invocable = (Invocable)engine;
				Object result = invocable.invokeFunction("getDatetime");
				System.out.println(result);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
